import { $getPiccInvoiceList } from "@/api/userCenter/applyInvoice/applyInvoice";
import { defineComponent, reactive, ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import styles from "./invoiceHistory.module.less";
import useDownload from "@/hooks/useDownload";

export default defineComponent({
  name:'userCenterInvoiceHistory',
  setup() {
    const router = useRouter();
    const download = useDownload();

    const searchForm = reactive({
      form: {
        channel: undefined,    //开票渠道
        company: undefined,    //保险公司
        orderid: null,           //单号
        invoiceHeader: null,     //发票抬头
        startDate: '',           //申请开始日期
        endDate: '',             //申请结束时间
        time: [],                //申请时间
      },
    })

    //查询
    const clickSearch = () => {
      console.log(String((new Date(searchForm.form.time[0]).getTime())))
      getList();
    }
    //重置
    const reset = () => {
      searchForm.form.invoiceHeader = null;
      searchForm.form.orderid = null;
      searchForm.form.time = [];
    }
    //时间change
    const timeChange = () => {
      if (searchForm.form.time === null) {
        searchForm.form.time = [];
      }
    }
    //查询条件
    const Search = () => (
      <div class={styles['search-box']}>
        <div class={styles['search-form']}>
          <div class={styles['search-form-row']}>
            <div class={styles['search-form-item']}>
              <div class={styles.label}>发票抬头：</div>
              <a-input style="width:50%;height:32px;" placeholder="请输入发票抬头" v-model:value={searchForm.form.invoiceHeader}></a-input>
            </div>
            <div class={styles['search-form-item']}>
              <div class={styles.label}>保单号：</div>
              <a-input style="width:50%;height:32px;" placeholder="请输入保单号" v-model:value={searchForm.form.orderid}></a-input>
            </div>
          </div>
          <div class={styles['search-form-row']}>
            <div class={styles['search-form-item']}>
              <div class={styles.label}>申请日期：</div>
              <a-range-picker v-model:value={[searchForm.form.time]} valueFormat="YYYY-MM-DD" style="margin-left: 10px;" onChange={() => { timeChange() }}></a-range-picker>
            </div>
            <div class={styles['search-form-item']}>

              <div class={[styles['searchBtn'], styles.plain]} onClick={() => { reset() }}>重置</div>
              <div class={styles['searchBtn']} onClick={() => { clickSearch() }}>查询</div>
            </div>
          </div>
        </div>
      </div>
    )
    const invoiceListState = reactive({
      columns: [
        {
          title: "序号",
          dataIndex: "id",
          key: "id",
          align: "center",
          width: "80px",
        },
        {
          title: "申请日期",
          dataIndex: "create_time",
          align: "center",
          width: "180px",
        },
        {
          title: "发票流水号",
          dataIndex: "picc_invoice_no",
          align: "center",
          width: "150px",
        },
        {
          title: "发票抬头",
          dataIndex: "title",
          align: "center",
          width: "150px",
        },
        {
          title: "发票金额(元)",
          dataIndex: "fee",
          align: "center",
          width: "120px",
        },
        {
          title: "银行账户",
          dataIndex: "bank_account",
          align: "center",
          width: "120px",
        },
        {
          title: "纳税人识别号",
          dataIndex: "buyer_tax_no",
          align: "center",
          width: "120px",
        },
        {
          title: "电子发票代码",
          dataIndex: "code",
          align: "center",
          width: "150px",
        },
        {
          title: "电子发票号码",
          dataIndex: "invoice_no",
          align: "center",
          width: "150px",
        },
        {
          fixed: "right",
          title: "操作",
          dataIndex: "operation",
          align: "center",
          width: "100px",
        }
      ],
      dataSource: [],
      selectedRowKeys: [],
      total: 24,
      pagination: {
        total: 1,
        current: 1,
        pageSize: 10,
      },
      loading: false,
    } as any)
    //选中项变更
    const onSelectChange = (changableRowKeys: any[]) => {
      invoiceListState.selectedRowKeys = changableRowKeys;
    };

    const rowSelection = computed(() => {
      return {
        selectedRowKeys: invoiceListState.selectedRowKeys,
        fixed: true,
        onChange: onSelectChange,
      }
    })

    //获取列表
    const getList = () => {
      invoiceListState.loading = true
      $getPiccInvoiceList({
        page: invoiceListState.pagination.current,
        limit: invoiceListState.pagination.pageSize,
        title: searchForm.form.invoiceHeader || undefined,
        policy_no:searchForm.form.orderid || undefined,
        applicant_begin_time: searchForm.form.time.length > 0 ? String((new Date(searchForm.form.time[0]).getTime() / 1000).toFixed(0)) : undefined,
        applicant_end_time: searchForm.form.time.length > 0 ? String((new Date(searchForm.form.time[1]).getTime() / 1000).toFixed(0)) : undefined,
      }).then((res: any) => {
        invoiceListState.loading = false;
        invoiceListState.dataSource = res.data?.data || [];
        invoiceListState.pagination.total = res?.data?.total || '';
        invoiceListState.pagination.current = res.data?.current_page || '';
        invoiceListState.pagination.pageSize = res?.data?.per_page || '';
      }).catch(() => {
        invoiceListState.loading = false;
      })
    }

    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      invoiceListState.pagination.current = pag.current;
      invoiceListState.pagination.pageSize = pag.pageSize;
      getList();
      // const dom: any = document.getElementById("app");
      // dom.scrollTop = 250;
    };

    onMounted(() => {
      getList()
    })

    //批量下载
    const downloadBtn = () => {
      invoiceListState.selectedRowKeys.forEach((url: any) => {
        download.downloadFile(url)
      })
    }
    return () => (
      <div class={styles.invoiceHistory}>
        <div class={styles['header-box']}>
          <span>开票历史</span>
        </div>
        <div class={styles['invoiceHistory-content']}>
          <Search />
          <div class={styles.hository}>
            <p>共查询到<span>{invoiceListState.pagination.total}</span>条数据</p>
            <div class={styles['downloadBtn']} onClick={() => { downloadBtn() }}>批量下载发票</div>
          </div>
          <a-table
            columns={invoiceListState.columns}
            bordered={true}
            scroll={{ x: "max-content" }}
            onChange={tableChangeHandler}
            dataSource={invoiceListState.dataSource}
            row-selection={rowSelection.value}
            rowKey="oss_url"
            pagination={invoiceListState.pagination}
            loading={invoiceListState.loading}
            v-slots={{
              bodyCell: ({ column, record }: any) => {
                // 操作栏
                if (column.dataIndex === "operation") {
                  return (
                    <div class="operation">
                      <a-button
                        type="primary"
                        size="small"
                        onClick={() => {
                          router.push(`/userCenter/invoiceHistory/details?invoice_no=${record.picc_invoice_no}`)
                        }}
                      >查看详情</a-button>
                      <a-button
                        type="primary"
                        size="small"
                        onClick={() => { download.downloadFile(record.oss_url) }}
                      >下载发票</a-button>
                    </div>
                  );
                }
              },
            }}
          ></a-table>
        </div>
      </div>
    )
  }
})